<template>
	<div class="wareHous-container">
		<el-card shadow="hover" :body-style="{ paddingBottom: '0' }">
			<el-form :model="state.queryParams" ref="queryForm" :inline="true">
				<el-form-item label="仓库代码">
					<el-input v-model="state.queryParams.warehousCode" placeholder="仓库代码" clearable />
				</el-form-item>
				<el-form-item label="库位名称">
					<el-input v-model="state.queryParams.code" placeholder="库位代码" clearable />
				</el-form-item>
				<el-form-item label="点位">
					<el-input v-model="state.queryParams.poiint" placeholder="点位" clearable />
				</el-form-item>
				<el-form-item>
					<el-button-group>
						<el-button type="primary" icon="ele-Search" @click="handleQuery" > 查询
						</el-button>
						<el-button icon="ele-Refresh" @click="resetQuery"> 重置 </el-button>
					</el-button-group>
				</el-form-item>
				<el-form-item>
					<el-button-group>
						<el-button type="primary" icon="ele-Plus" @click="addWare"
							>添加</el-button>
							<el-button type="primary" icon="ele-Download" @click="downloadTemplate"
							>模版</el-button>
							<el-button type="primary" icon="ele-Download" @click="exportDate"
							>导出</el-button>
							<el-button type="danger"  icon="ele-Warning" @click="batchDeletePosition">批量删除</el-button>
					</el-button-group>
					
						
						<el-upload class="upload-demo" :http-request="handleUpload" :show-file-list="false" :before-upload="beforeUpload" 
							:on-success="handleUploadSuccess" :on-error="handleUploadError">
							<el-button icon="ele-Upload" >导入</el-button>
						</el-upload>
						
				</el-form-item>
					
			</el-form>
		</el-card>

		<el-card class="full-table" shadow="hover" style="margin-top: 5px">
			<el-table :data="state.wareHousPositionData" style="width: 100%" v-loading="state.loading" border
				@selection-change="handleSelectionChange">
				<el-table-column type="selection" prop="id" width="55" align="center" />
				<el-table-column type="index" label="序号" width="55" align="center" />
				<el-table-column prop="warehousCode" label="仓库代码" align="center" show-overflow-tooltip />
				<el-table-column prop="code" label="库位代码" align="center" show-overflow-tooltip />
				<el-table-column prop="poiint" label="点位" align="center" show-overflow-tooltip />
				<el-table-column prop="createTime" label="创建时间" align="center" show-overflow-tooltip />
				<el-table-column prop="channelLocation" label="通道点位" align="center" show-overflow-tooltip />
				<el-table-column prop="storey" label="楼层" align="center" show-overflow-tooltip />
				<el-table-column prop="qrcode" label="二维码" align="center" show-overflow-tooltip />
				
				<el-table-column prop="isenable" label="冻结" width="80" align="center">
					<template #default="scope">
						<el-checkbox v-model="scope.row.isenable" :disabled="true" :true-label="0" :false-label="0">
							<!-- {{ scope.row.isenable === 1 ? '启用' : '禁用' }} -->
						</el-checkbox>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="140" fixed="right" align="center" show-overflow-tooltip>
					<template #default="scope">
						<el-button icon="ele-Edit" size="small" text type="primary" @click="openEditWarehous(scope.row)"
							> 编辑 </el-button>
						<el-button size="small" text type="danger" @click="delWarehous(scope.row)"
							> 删除 </el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination v-model:currentPage="state.tableParams.page" v-model:page-size="state.tableParams.pageSize"
				:total="state.tableParams.total" :page-sizes="[10, 20, 50, 100]" size="small" background
				@size-change="handleSizeChange" @current-change="handleCurrentChange"
				layout="total, sizes, prev, pager, next, jumper" />
		</el-card>

		<EditPosition ref="editPositionRef" :title="state.editWarehousTitle" @handleQuery="handleQuery" />
	</div>
</template>

<script lang="ts" setup name="position">
import { onMounted, computed, reactive, ref } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import EditPosition from './component/editPosition.vue';
import { getAPI } from '/@/utils/axios-utils';
import { WarehousePositionApi, WarehousePositionexportApi,WarehousePositioninportApi,DownloadWarehousePositionApi ,BatchDeletePositionApi} from '/@/api-services/apis/warehouse-position-api'; // 导入 API 服务
import { WarehousePosition,DeleteWarehousePositionInput } from '/@/api-services/models/warehouse-position-input'; // 导入库位实体
import { WarehouseInput } from '/@/api-services/models/warehouse-input'; // 导入仓库实体添加编辑下拉
import { error } from 'console';
import { Position } from '@vueuse/core';
import { json } from 'stream/consumers';
import { downloadByData, getFileName } from '/@/utils/download';
import { costByPoints } from '@logicflow/core';

// ...其他导入

const editPositionRef = ref<InstanceType<typeof EditPosition>>();
const state = reactive({
	loading: false,
	wareHousPositionData: [] as Array<WarehousePosition>,
	wareHousData: [] as Array<WarehouseInput>,

	queryParams: {
		warehousCode: undefined,
		code: undefined,
		poiint: undefined,
	},
	tableParams: {
		page: 1,
		pageSize: 50,
		total: 0,
	},
	editWarehousTitle: '',

});

onMounted(async () => {
	handleQuery();
});




// 查询操作
const handleQuery = async () => {
	state.loading = true;
	try {
		const res = await getAPI(WarehousePositionApi).apiWarehousePositionPageGet({
			...state.queryParams,
			page: state.tableParams.page,
			pageNumber: state.tableParams.page,
			pageSize: state.tableParams.pageSize,
		});
		state.wareHousPositionData = res.data.result?.items || [];
		state.tableParams.total = res.data?.result?.total ?? 0;

	} catch {
		state.wareHousData = [];
		state.tableParams.total = 0;
	}

	finally {
		state.loading = false;

	}
};

// 重置操作
const resetQuery = () => {
	state.queryParams.warehousCode = undefined;
	state.queryParams.code = undefined;
	state.queryParams.poiint = undefined;
	handleQuery();
};

// 打开新增页面
const addWare = () => {
	const addData = {
		warehousCode: undefined,
		code: undefined,
		poiint: undefined,
		isenable: 0,
		// wareHousData: [] as Array<WarehouseInput>,
	};
	state.editWarehousTitle = '添加库位';
	editPositionRef.value?.openDialog(addData);
};

// 假设存在一个方法可以获取选中行的数据，这里我们先定义一个 ref 来存储选中的行
const multipleSelection = ref<DeleteWarehousePositionInput[]>([]);

const handleSelectionChange = (val: any[]) => {
	multipleSelection.value = val;
};
// 获取选中行的 idlist
const selectedIds = computed(() => multipleSelection.value.map(item => ({id:item.id})));
const batchDeletePosition = async (d: number) => {

try {
	if(selectedIds.value.length === 0){
		ElMessage.error('请选择要操作的记录');
		return;
	}
		const res = await BatchDeletePositionApi(selectedIds.value);
	
// 检查 res 是否存在，避免出现未定义错误
if (res.status === 200) {
		ElMessage.success('操作成功');
		handleQuery();
	}
	else {
		ElMessage.error('操作失败');
	}
} catch (error) {
	ElMessage.error('操作失败');
}
};


// 关闭新增页面
const closeAddDialog = () => {
	editPositionRef.value?.openDialog(false);
};



// 打开编辑页面
const openEditWarehous = (row: any) => {
	state.editWarehousTitle = '编辑库位档案';
	editPositionRef.value?.openDialog(row);
};

// 删除操作
const delWarehous = (row: any) => {
	ElMessageBox.confirm(`确定删除【${row.warehousCode}】仓库下的库位：【${row.code}】?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			try {
				await getAPI(WarehousePositionApi).apiWarehousePositionDeletePost({ id: row.id });
				handleQuery();
				ElMessage.success('删除成功');
			} catch (error) {
				ElMessage.error('删除失败，请稍后重试');
			}
		})
		.catch(() => {
			ElMessage.info('已取消删除');
		});
};


const exportDate = async () => {
	try {
		state.loading = true;
// 通常导出文件时需要设置 responseType 为 'blob'，以正确处理二进制数据
// 为了解决类型不匹配问题，将 responseType 单独传递
const config = { responseType: 'blob' };
var res = await WarehousePositionexportApi(state.queryParams);
		state.loading = false;
		var fileName = getFileName(res.headers);
		// 假设增加一些日志记录，方便调试
		console.log('准备开始下载文件，文件数据:', res.data, '文件名:', fileName);
		downloadByData(res.data as any, fileName);
		ElMessage.success('导出成功' + fileName);
	}
	catch (error) {
		state.loading = false;
		ElMessage.error('导出失败');
	}
}

// #region 导入
// 上传前校验
const beforeUpload = (file: File) => {
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
                  file.type === 'application/vnd.ms-excel'
  if (!isExcel) {
    ElMessage.error('只能上传 Excel 文件!')
    return false
  }
  return true
}
// 自定义上传方法
const handleUpload = async (options: any) => {
  
    const formData = new FormData()
    formData.append('file', options.file)
    // 这里调用你的上传API
try {
  const response = await WarehousePositioninportApi(formData);
  handleUploadSuccess(response);
} catch (error) {
  handleUploadError(error);
}
}

// 上传成功回调
const handleUploadSuccess = (response: any) => {
  if (response.status === 200) {
    ElMessage.success('导入成功')
    handleQuery() // 刷新表格数据
  } 
  else {
    ElMessage.error(response.message || '导入失败')
  }
}

// 上传失败回调
const handleUploadError = (error:any) => {
	  ElMessage.error(error.message || '导入失败')
}



const downloadTemplate = async () => {
  try {
     DownloadWarehousePositionApi().then((response)=>{
		
     const blob=new Blob([response.data])
	 const fileName=getFileName(response.headers);
	 downloadByData(response.data as any, fileName);
	//  if ('download' in document.createElement('a')) {
    //   const elint = document.createElement('a')
    //   elint.download = fileName
    //   elint.style.display = 'none'
    //   elint.href = URL.createObjectURL(blob)
    //   document.body.appendChild(elint)
    //   elint.click()
    //   URL.revokeObjectURL(elint.href)
    //   document.body.removeChild(elint)
    // } else {
    //   // 兼容IE浏览器下载
    //   (navigator as any).msSaveBlob(blob, fileName)
    // }
     ElMessage.success(`下载成功${fileName}`);
	 }); // 调用下载模板的API

  } catch (error) {
    ElMessage.error('下载失败');
  }
};
// 改变页面容量
const handleSizeChange = (val: number) => {
	state.tableParams.pageSize = val;
	handleQuery();
};

// 改变页码序号
const handleCurrentChange = (val: number) => {
	state.tableParams.page = val;
	handleQuery();
};
</script>
